72. HTTP客户端

72.1 配置RestTemplate使用代理

正如Section 33.1, “RestTemplate customization”描述的那样,你可以使用RestTemplateCustomizerRestTemplateBuilder构建一个自定义的RestTemplate,这是创建使用代理的RestTemplate的推荐方式。

代理配置的确切细节取决于底层使用的客户端请求factory,这里有个示例演示HttpClient配置的HttpComponentsClientRequestFactory对所有hosts都使用代理,除了192.168.0.5

static class ProxyCustomizer implements RestTemplateCustomizer {

    @Override
    public void customize(RestTemplate restTemplate) {
        HttpHost proxy = new HttpHost("proxy.example.com");
        HttpClient httpClient = HttpClientBuilder.create()
                .setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {

                    @Override
                    public HttpHost determineProxy(HttpHost target,
                            HttpRequest request, HttpContext context)
                                    throws HttpException {
                        if (target.getHostName().equals("192.168.0.5")) {
                            return null;
                        }
                        return super.determineProxy(target, request, context);
                    }

                }).build();
        restTemplate.setRequestFactory(
                new HttpComponentsClientHttpRequestFactory(httpClient));
    }

}